import { InfoCircleOutlined } from '@ant-design/icons'
import { useModel, useParams } from '@umijs/max'
import { Button, Form, Modal, Result, Select, Steps, App, Input } from 'antd'
import { useState } from 'react'
import './OldCreditBtnGroup.less'

const formItemLayout = { labelCol: { span: 4 }, wrapperCol: { span: 20 } }

const creditBtnList = [
  {
    key: 'query_credit',
    name: '申请查询征信',
    bgColor: '#FFF7E8',
    color: '#FF7D00'
  },
  {
    key: 'query_credit_result',
    name: '查看征信结果',
    bgColor: '#FFECE8',
    color: '#F53F3F'
  },
  {
    key: 'open_account',
    name: '开户上报',
    bgColor: '#FFECE8',
    color: '#F53F3F'
  },
  {
    key: 'add_water',
    name: '追加流水',
    bgColor: '#D8E4FF',
    color: '#165DFF'
  },
  {
    key: 'settle',
    name: '账户结清',
    bgColor: '#E8FFEA',
    color: '#00B42A'
  }
]

function CreditBtnGroup({ leaseTerm }) {
  const routerParams = useParams()
  const { id } = routerParams
  const order_id = id

  const { CreditQueryCreate, GetQueryCreditResult, CreditLoanReport, CreditRepay, CreditSettle, CreditGetReportFile } =
    useModel('RiskControl')

  const { setIsLoading } = useModel('Global')

  const [modalConfirmLoading, setModalConfirmLoading] = useState(false) // 弹窗确认按钮loading
  const [creditReportingModal, setCreditReportingModal] = useState(false) // 弹窗

  const [btnLoading, setBtnLoading] = useState(false) // 按钮loading

  const { message, modal } = App.useApp()

  const [currentReportingEvent, setCurrentReportingEvent] = useState('') // 当前征信上报事件

  const [orderBillNum, setOrderBillNum] = useState([]) // 账单期数

  const [openAccountFormRef] = Form.useForm() // 开户上报
  const [addWaterFormRef] = Form.useForm() // 追加流水

  // 开户上报资料
  const [openAccountData, setOpenAccountData] = useState({})

  // 打开弹窗按钮
  const handleReporting = async item => {
    setBtnLoading(true)

    // 开户上报重置
    if (item.key === 'open_account') {
      message.warning('数据生成中,请稍等...')
      openAccountFormRef.resetFields()
      // 获取并生成上报文件
      const res = await CreditGetReportFile({
        order_id
      })
      if (res) {
        const { contractUrl, idContractUrl } = res
        setOpenAccountData({
          contractUrl,
          idContractUrl
        })
      } else {
        setBtnLoading(false)
        return
      }
    }

    // 追加流水重置
    if (item.key === 'add_water') {
      if (leaseTerm) {
        let list = []
        // eslint-disable-next-line array-callback-return
        Array.from({ length: leaseTerm }).map((_, index) => {
          list.push({
            value: index + 1,
            label: `第 ${index + 1} 期`
          })
        })

        setOrderBillNum(list)
      }
      addWaterFormRef.resetFields()
    }

    setBtnLoading(false)
    setCurrentReportingEvent(item)
    setCreditReportingModal(true)
  }

  // 定义处理事件的对象
  const handleEventObj = {
    query_credit: {
      title: '申请征信查询',
      modelConfirmEvent: async () => {
        let res = await CreditQueryCreate({ order_id })
        if (res) {
          message.success('申请征信查询成功')
          setCreditReportingModal(false)
        }
      }
    },
    query_credit_result: {
      title: '征信查询结果',
      modelConfirmEvent: async () => {
        let res = await GetQueryCreditResult({ order_id })
        if (res) {
          message.success('征信结果查询成功')
          setCreditReportingModal(false)
          window.open(res.creditUrl)
        }
      }
    },
    open_account: {
      title: '开户上报',
      modelConfirmEvent: async () => {
        try {
          await openAccountFormRef.validateFields()
          let params = {
            order_id,
            ...openAccountFormRef.getFieldsValue(),
            ...openAccountData
          }

          let res = await CreditLoanReport(params)
          if (res) {
            message.success('开户上报成功')
            setCreditReportingModal(false)
          }
        } catch (e) {
          setModalConfirmLoading(false)
        }
      }
    },
    add_water: {
      title: '追加流水',
      modelConfirmEvent: async () => {
        try {
          await addWaterFormRef.validateFields()
          let params = {
            order_id,
            ...addWaterFormRef.getFieldsValue()
          }
          let res = await CreditRepay(params)
          if (res) {
            message.success('追加还款流水成功')
            setCreditReportingModal(false)
          }
        } catch (e) {
          setModalConfirmLoading(false)
        }
      }
    },
    settle: {
      title: '账户结清',
      modelConfirmEvent: async () => {
        let res = await CreditSettle({ order_id })
        if (res) {
          message.success('结清成功')
          setCreditReportingModal(false)
        }
      }
    }
  }

  // 处理弹窗确认事件
  const creditReportingModalConfirm = async () => {
    const { key } = currentReportingEvent
    setModalConfirmLoading(true)
    let res = await handleEventObj[key].modelConfirmEvent()
    if (!res) {
      setModalConfirmLoading(false)
    }
  }

  // 渲染步骤提示内容
  const renderTipsText = (key, text) => {
    return (
      currentReportingEvent?.key === key && (
        <div className='tips_text'>
          <InfoCircleOutlined style={{ color: '#FF7D00' }} /> {text}
        </div>
      )
    )
  }

  return (
    <div>
      <div className='header_credit'>
        <div key='header_content'>
          {creditBtnList.map(item => {
            return (
              <Button
                loading={btnLoading}
                key={item.key}
                style={{
                  background: item.bgColor,
                  color: item.color,
                  border: `1px solid ${item.color}`,
                  marginLeft: '10px'
                }}
                onClick={() => handleReporting(item)}
              >
                {item.name}
              </Button>
            )
          })}
        </div>
      </div>

      {/* 开户上报 */}
      <Modal
        title={currentReportingEvent?.name}
        mask
        open={creditReportingModal}
        bodyStyle={{ padding: '20px 0' }}
        width={640}
        confirmLoading={modalConfirmLoading}
        onCancel={() => setCreditReportingModal(false)}
        onOk={() => creditReportingModalConfirm()}
        okText={'确认'}
        maskClosable={false}
      >
        {renderTipsText('query_credit', '您确定需要查询该用户征信吗?')}

        {renderTipsText('query_credit_result', '确认查询后将会进行征信数据展示?')}

        {
          /* 开户上报 */
          currentReportingEvent?.key === 'open_account' && (
            <Form form={openAccountFormRef} name='open_account' {...formItemLayout}>
              <Form.Item
                name='houseAddressArea'
                label='户籍地址 : '
                extra='例如 : 西湖区'
                rules={[{ required: true, message: '请输入户籍地址' }]}
              >
                <Input placeholder='请输入户籍地址' allowClear />
              </Form.Item>
              <Form.Item
                name='houseAddress'
                label='户籍详情地址 : '
                extra='例如 : 浙江省杭州市西湖区西兴街道'
                rules={[{ required: true, message: '请输入户籍详情地址' }]}
              >
                <Input placeholder='请输入户籍详情地址' allowClear />
              </Form.Item>
            </Form>
          )
        }

        {
          /* 追加流水 */
          currentReportingEvent?.key === 'add_water' && orderBillNum.length > 0 && (
            <Form form={addWaterFormRef} name='add_water' {...formItemLayout}>
              <Form.Item name='bill_num' label='期数 : ' rules={[{ required: true, message: '请选择期数' }]}>
                <Select placeholder={'请选择期数'} options={orderBillNum} />
              </Form.Item>
            </Form>
          )
        }

        {renderTipsText('settle', '您确定账户已结清吗?') /* 账户结清 */}
      </Modal>
    </div>
  )
}

export default CreditBtnGroup
